package Screens;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import resource.FinishGameScreen;
import resource.HighScoreStore;

import Game.CanvasGame;
import Objects.Statistic;

public class FinishGame extends Screen {
	private Image[] img;
	private int stt;
	private Statistic statistic;
	private static long startTime; 
	private long currTime;
	private HighScoreStore hs;

	public FinishGame(CanvasGame _canvas, int stt, Statistic statistic) {
		super(_canvas);
		// TODO Auto-generated constructor stub
		startTime = System.currentTimeMillis();
		currTime = 0;
		this.stt = stt;
		this.statistic = statistic;
		img = new Image[FinishGameScreen.IMG_LENGHT];
		hs = new HighScoreStore();
		load_screen();
	}

	public Statistic getStatistic() {
		return statistic;
	}

	public void setStatistic(Statistic statistic) {
		this.statistic = statistic;
	}

	public void load_screen() {
		// TODO Auto-generated method stub
		for (int i = 0; i < FinishGameScreen.IMG_LENGHT; i++) {
			load(i);
		}
	}
	
	public void un_load_screen() {
		// TODO Auto-generated method stub
		//img = null;
		if(img == null)    return;
        for (int i = 0; i < FinishGameScreen.IMG_LENGHT; i++) {
            unLoad(i);
        }
	}


	public boolean load(int i) {
		/* TODO: load the images here */
	    try {
	    	img[i] = Image.createImage(FinishGameScreen.imgSource[i]);
	    } catch (Exception ex) {
	    	System.err.println(ex.toString()+"aaaa");
	    	return false;
	    }
	    return true;
	}
	
	public void unLoad(int i) {
        /* TODO: make sure the object get's destroyed */
        img[i] = null;
    }
	public void keyEvent(int keycode, int event) {
		// TODO Auto-generated method stub

	}

	public void ActionClick(int i) {
		// TODO Auto-generated method stub

	}

	public void update() {
		// TODO Auto-generated method stub

	}

	public void paint(Graphics g) {
		// TODO Auto-generated method stub
		
		if (currTime - startTime < 3000) {
			currTime = System.currentTimeMillis();
			if(stt == FinishGameScreen.WIN){
				g.drawImage(img[FinishGameScreen.MENU_WIN], 0, 0, Graphics.TOP|Graphics.LEFT);
				hs.open();
				if(hs.isTop(statistic)){
					canvas.setScreen(new SaveScore(canvas, statistic));
				}
				hs.close();
			}
			else{
				g.drawImage(img[FinishGameScreen.MENU_LOSE], 160, 120, Graphics.VCENTER|Graphics.HCENTER);
				
			}
		}
		else{
			un_load_screen();
			canvas.setScreen(new Menu(canvas));
		}
	}
}
